var teachList = (function ($) {
	var teachPull
	var sourceData=[];
	var page = 0,Limit = 20;
	var pulling = false;
	var pageType="",loginID='',teachFlag='T';
	$.init();
	$.plusReady(function () {
	    baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup()
	}
	
	function getTeachData(){
		if (pulling) {
			teachPull.endPullUpToRefresh()
			return;
		}
		pulling = true
		var ymDate = $('#ymDate')[0].innerText
		var arr = ymDate.split('-')
		var OD = $('#cate')[0].getAttribute('data-id') // Y必修 N选修 1是主题
		var maxDay = getMonthMaxDay(parseInt(arr[0]),parseInt(arr[1]))
		var parr = ymDate+'-01^'+ymDate+'-'+maxDay+'^1^'+OD+'^'+teachFlag; 
		//var parr = '^^1^^T'; 
		var pdict = {'parr':parr,'input':$('#search')[0].value,'loginID':loginID,'start':page,'limit':Limit}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:FindDrillReleaseList','params':JSON.stringify(pdict),'type':'RecQuery'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			pulling = false
			if (result['msgcode'] != '1') {
				mui.toast(result.msg)
				teachPull.endPullUpToRefresh();
				return
			}
			var dataArr = result.data
			if (page == 0) {
				sourceData = dataArr
				$('#UL')[0].innerHTML = ''
			}else{
				sourceData = sourceData.concat(dataArr)
			}
			updateUI(dataArr)
			if (dataArr.length < Limit) {
				teachPull.endPullUpToRefresh(true);
			}else{
				teachPull.endPullUpToRefresh();
			}
			page += dataArr.length;
		}, function(errorStr) {
			teachPull.endPullUpToRefresh();
			pulling = false
		});
	}
	
	function updateUI(dataArr){
		var UL = $('#UL')[0]
		var oldcount = UL.querySelectorAll('li').length
		for(var i=0; i < dataArr.length; i++){
			var dict = dataArr[i]
			var wayDesc = ''
			if (dict['ReleaseWay'] == 'O') {
				wayDesc = '上'
			}else if (dict['ReleaseWay'] == 'D') {
				wayDesc = '下'
			}
			var levelDesc = ''//H:院级,L:科级,W:病区
			var level = dict['ReleaseLevel']
			if (level == 'H') {
				levelDesc = '院级'
			}else if (level == 'L') {
				levelDesc = '科级'
			}else if (level == 'W') {
				levelDesc = '病区'
			}
			var TypeDesc = dict['ReleaseDrillTypeDesc']||''
			var html = '<div class="classTitle">'+dict['ReleaseDesc']+'</div>'+
				//级别 类型 方式 讲师 学分
				'<div class="classInfo">'+(levelDesc==""?'':('<div>'+levelDesc+'</div>'))+
					(TypeDesc==""?'':('<div>'+TypeDesc+'</div>'))+
					(wayDesc==""?'':('<div>线'+wayDesc+'培训</div>'))+
					(dict['CoursesType']==""?'':('<div>'+(dict['CoursesType'] == 'Y'?'必修':'选修')+'</div>'))+
					(dict['DrillCredit']==""?'':('<div>'+dict['DrillCredit']+'分</div>'))+'</div>'+
				'<div class="classSubInfo">培训日期：'+dict['StartDate']+' - '+dict['EndDate']+'</div>'
			if(wayDesc == '下'){
				//TimeList: "2023-07-19 00:00」2023-08-19 00:00」2023-07-31 00:00」考核地点」5「2023-08-19 00:00」2023-09-19 00:00」2023-08-31 00:00」考核地点2」2「2023-09-19 00:00」2023-10-19 00:00」2023-09-30 00:00」考核地点3」3"
				// html += '<div class="classSubInfo">课程时间：2021.06.15 10:00 - 2021.06.15 11:00</div>'+
				// '<div class="classSubInfo">培训地点：阶梯教室101</div>'
				var TimeList = dict['TimeList'].split('「')
				for (var j = 0; j < TimeList.length; j++) {
					var oneTime = TimeList[j].split('」')//开始日期」截止日期」预约截止时间」考核时间」考核地点」人数上限
					html += '<div class="classSubInfo">【'+(j+1)+'】课程时间：'+oneTime[0]+'-'+oneTime[1]+'</div>'+
						'<div class="classSubInfo">【'+(j+1)+'】培训地点：'+oneTime[3]+'</div>'
				}
				
				
			}
			if (dict['startStatus'] == 'N') {
				html +='<div class="process noStart">未开始</div>'
			}else if (teachFlag == 'T'){
				html += '<div class="mui-btn mui-btn-primary baseBtn credit" id="'+(oldcount+i)+'">授予学分</div>'
				if (dict['TeacherStudentDR'] != '') { //有评价
					html +='<div class="mui-btn mui-btn-primary baseBtn survey" id="'+(oldcount+i)+'">问卷调查</div>'
				}
				if (wayDesc == '上'){
					html +='<div class="mui-btn mui-btn-primary baseBtn answer" id="'+(oldcount+i)+'">回答问题</div>'
				}
				html += '<div class="mui-btn mui-btn-primary baseBtn result" id="'+(oldcount+i)+'">查看结果</div>'
			}else{
				html += '<div class="mui-btn mui-btn-primary baseBtn result" id="'+(oldcount+i)+'">查看结果</div>'
			}
			var newLi = document.createElement('li')
			UL.appendChild(newLi)
			newLi.setAttribute('class','mui-table-view-cell')
			newLi.innerHTML = html
			newLi.id = (oldcount + i)
		}
	}
	
	//问卷
	function surveyBtnTapped(){
		var btnId = this.id;
		var dict = sourceData[btnId]
		var webview = plus.webview.create('teachSurveyList.html', 'teachSurveyList', {
			background: '#fff',
			statusbar: {
				background: '#fff'
			}
		},{sourceData:dict});
		webview.show('fade-in');
	}
	//回答问题
	function answerBtnTapped(){
		var dict = sourceData[this.id]
		var webview = plus.webview.create('teachAnswer.html', 'teachAnswer', {
			background: '#fff',
			statusbar: {
				background: '#fff'
			}
		},{sourceData:dict});
		webview.show('fade-in');
	}
	//授予学分
	function creditBtnTapped(){
		var index = this.id
		var dict = sourceData[index]
		var webview = plus.webview.create('teachCredit.html', 'teachCredit', {
			background: '#fff',
			statusbar: {
				background: '#fff'
			}
		},{pageType:'teachCredit',sourceData:dict});
		webview.show('fade-in');
	}
	function resultBtnTapped(){
		var index = this.id
		var dict = sourceData[index]
		var webview = plus.webview.create('teachCredit.html', 'teachCredit', {
			background: '#fff',
			statusbar: {
				background: '#fff'
			}
		},{pageType:'teachResult',sourceData:dict});
		webview.show('fade-in');
	}
	function baseSetup(){
		//初始化日期
		var today = getCurrentDeviceDay()
		$('#ymDate')[0].innerText = today.substring(0,7)
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		var perInfo = app.getState()
		loginID = perInfo['loginID']
		var self = plus.webview.currentWebview()
		pageType = self.pageType;
		if (pageType == 'tongji') { //title
			$('.mui-title')[0].innerText = '培训统计'
			teachFlag = ''
		}else{
			$('.mui-title')[0].innerText = '讲师培训'
		}
		$('.filterArea').on('tap','.ymArea',selectYearMonth);
		$('.filterArea').on('tap','.method',function(){
			$('.filterArea .method')[0].classList.add('mui-active')
			$('#trainMethod').popover('toggle')
		});
		$('.filterArea').on('tap','.cate',function(){
			$('.filterArea .cate')[0].classList.add('mui-active')
			$('#trainCate').popover('toggle')
		});
		mui('body').on('hidden', '.mui-popover', function(e) {
			if(this.id == 'trainCate') {
				$('.filterArea .cate')[0].classList.remove('mui-active')
			}else if (this.id == 'trainMethod') {
				$('.filterArea .method')[0].classList.remove('mui-active')
			}
		});
		mui('body').on('tap','.mui-dtpicker-header > button',function(e){
			$('.filterArea .ymArea')[0].classList.remove('mui-active')
		});
		mui("body").on("tap",".mui-backdrop",function(){
			$('.filterArea .ymArea')[0].classList.remove('mui-active')
		})
		
		$('.trainMethod').on('tap','li',function(){
			var oldActive = $('#trainMethod .dhc-active')[0]
			if (oldActive == this) {
				return
			}
			if (oldActive) {
				oldActive.classList.remove('dhc-active');
			}
			this.classList.add('dhc-active');
			$('#method')[0].innerHTML = this.innerHTML
			$('#trainMethod').popover('toggle')
		});
		$('.trainCate').on('tap','li',function(){
			var oldActive = $('#trainCate .dhc-active')[0]
			if (oldActive == this) {
				return
			}
			if (oldActive) {
				oldActive.classList.remove('dhc-active');
			}
			this.classList.add('dhc-active');
			$('#cate')[0].innerHTML = this.innerHTML
			$('#trainCate').popover('toggle')
		});
		
		mui("body").on("tap", ".searchArea .mui-icon-clear", function() {
			if (document.getElementById('search').value != "") {
				document.getElementById('search').value = ""
			}
			resetTeachRefresh()
		});
		mui('#wrapper').on('tap','.answer',answerBtnTapped)	//线上课程才有回答问题
		mui('#wrapper').on('tap','.survey',surveyBtnTapped)	//问卷调查
		mui('#wrapper').on('tap','.credit',creditBtnTapped) //授予学分
		mui('#wrapper').on('tap','.result',resultBtnTapped) //查看结果
		
		var search = document.getElementById('search');
		search.addEventListener('input',function(){
			resetTeachRefresh();
		});
		var scroll = document.getElementById('scroll');
		teachPull = $(scroll).pullToRefresh({
			up: {
				callback: function() {
					getTeachData()
				}
			}
		});
		
		getTeachData();
	}
	function selectYearMonth() {
		var _self = this
		_self.classList.add('mui-active')
		if(_self.picker) {
			_self.picker.show(function(rs) {
				$('#ymDate')[0].innerHTML = rs.text
				_self.classList.remove('mui-active')
				_self.picker.dispose();
				_self.picker = null;
				
			});
		} else {
			var optionsJson = '{"type":"month"}';
			var options = JSON.parse(optionsJson);
			_self.picker = new mui.DtPicker(options);
			var height = screen.height;
			var width = screen.width;
			if (height < width) {
				height = width;
			}
			height -= 44;
			if (mui.os.plus) {
				height -= 20;
			}
			var bottom = height - $('.filterArea')[0].clientHeight - $('.searchArea')[0].clientHeight - 274;
			_self.picker.ui.picker.style.bottom = bottom + 'px';
			_self.picker.show(function(rs) {
				$('#ymDate')[0].innerHTML = rs.text
				_self.classList.remove('mui-active')
				_self.picker.dispose();
				_self.picker = null;
			});
		}
	}
	function resetTeachRefresh(){
		page = 1;
		sourceData = []
		if (teachPull) {
			teachPull.refresh(true)
		}
		getTeachData();
		$('#wrapper').scroll().scrollTo(0,0,100);
	}
	var exportObj = {}
	exportObj.updateSurveyUI = function(btnId){
		var dom = $('#'+btnId)[0]
		if (dom) {
			dom.parentNode.removeChild(dom)
		}
	};
	return exportObj
	
})(mui);

function refreshSurveyUI(data){
	teachList.updateSurveyUI(data);
}